package com.renu.jdependencyanalyser.visualizer;

import com.renu.jdependencyanalyser.cons.ProjectCons;
import com.renu.jdependencyanalyser.freemarker.AbstractProcessor;
import freemarker.template.TemplateException;

import java.io.IOException;

public class GraphvizVisualizer implements Visualizer{
    private static Runtime rt = Runtime.getRuntime();

    @Override
    public void generateGraph(AbstractProcessor processor, String filePath) {

        try {
            String dotCode = processor.process();
            // 使用 ProcessBuilder 执行 dot 命令
            ProcessBuilder processBuilder = new ProcessBuilder("dot", "-Tpng", "-o",filePath,"-Gdpi="+ProjectCons.DPI);
            Process process = processBuilder.start();

            // 将 Dot 代码写入 dot 命令的输入流
            process.getOutputStream().write(dotCode.getBytes());
            process.getOutputStream().close();

            // 等待 dot 命令执行结束
            int exitCode = process.waitFor();
            System.out.println("Dot command exit code: " + exitCode);



        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            throw new RuntimeException(e);
        }
    }
    //@Override
    public void generateGraph1(AbstractProcessor processor, String filePath) {
        // 命令字符串


        try {
            String dotCode = "digraph example { A -> B; }";
            String code = processor.process();
            //String command ="echo \'"+code +"\'"+" | dot -Tpng -o "+fileName;
            //String command = "echo \'" + code + "\'" + " | dot -Tpng -Gdpi=" + ProjectCons.DPI + " -o " + MyProjectUtil.projectBasePath + File.separator + "tmp.png";
            // 创建 ProcessBuilder 对象
            // 使用 ProcessBuilder 执行 dot 命令
            ProcessBuilder processBuilder = new ProcessBuilder("dot", "-Tpng", "-o", filePath);
            Process process = processBuilder.start();

            // 将 Dot 代码写入 dot 命令的输入流
            process.getOutputStream().write(dotCode.getBytes());


            // 等待 dot 命令执行结束
            int exitCode = process.waitFor();
            System.out.println("Dot command exit code: " + exitCode);
            //process.getOutputStream().close();
        } catch (TemplateException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (InterruptedException e) {
            System.out.println("DOT interrupted when processing " + filePath + "\nReason: " + e.toString() );
        }
    }
}

